<template>
  <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" size="small">
    <el-form-item label="图名称" prop="bannerName">
      <el-input v-model.trim="ruleForm.bannerName" placeholder="请输入图名称"></el-input>
    </el-form-item>
    <el-form-item label="图类型/位置" prop="bannerType">
      <el-select v-model="ruleForm.bannerType" placeholder="请选择类型" class="block">
        <el-option v-for="(i, k) in $attrs.bannerTypes" :key="k" :label="i.label" :value="i.value"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="商品类型" prop="bannerResourceType">
      <el-select v-model="ruleForm.bannerResourceType" placeholder="请选择资源类型" class="block">
        <el-option
          v-for="(it, i) in bannerResourceTypes"
          :key="i"
          :label="it.label"
          :value="it.value"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="关联" prop="bannerResource">
      <TagBox
        @close="handleClose"
        closable
        v-model="ruleForm.bannerResourceList"
        :props="tagBoxProps"
      >
        <div
          v-if="!!ruleForm.bannerResourceType"
          @click="openPickerTable"
          slot="footer"
          style="text-align: center;cursor: pointer;color: #1ab394;margin-left: -50px;"
        >打开列表</div>
      </TagBox>
    </el-form-item>

    <el-form-item label="图简介" prop="bannerSummary">
      <el-input v-model.trim="ruleForm.bannerSummary" placeholder="请输入图简介" type="textarea"></el-input>
    </el-form-item>

    <el-form-item label="图片地址" prop="bannerLocation">
      <el-input v-model="ruleForm.bannerLocation" class="hide" />
      <el-upload
        :action="$V.uploadURL"
        :headers="{token: $getToken()}"
        :on-success="handleUploadSuccess"
        :on-remove="handleUploadRemove"
        :on-error="handleUploadError"
        :file-list="bannerFileList"
        :class="single ? 'single' : ''"
        list-type="picture-card"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
    </el-form-item>

    <Modal
      :onOk="handlePick"
      :onCancel="() => pickerModalVisible = false"
      :visible.sync="pickerModalVisible"
      :loading="pickerModalLoading"
      :width="$V.size.lg"
      appenmodelBody
      okText="选择"
      cancelText="关闭"
      title="关联"
    >
      <Picker
        ref="picker"
        :crossPick="crossPick"
        :type="pickerType"
        :singlePick="singlePick"
        :lastPicked="ruleForm.bannerResourceList"
      />
    </Modal>
  </el-form>
</template>

<script>
/* Mixins
------------------------------- */
import { Form, Emitter } from '@/mixins'

/* Components
------------------------------- */
import TagBox from '@/components/tag-box/TagBox'
import Picker from './GoodsPicker'

/* Model
------------------------------- */
import { bannerModel } from '../model'
import { bannerResourceTypeEnum } from '@/core/enum'

export default {
  commentName: 'BannerForm',
  mixins: [Form('ruleForm', bannerModel), Emitter],
  components: { TagBox, Picker },
  data () {
    return {
      ruleForm: Object.assign({}, bannerModel),
      rules: {
        bannerName: [
          {
            required: true,
            message: this.$t('required', { field: '图名称' })
          }
        ],
        bannerType: [
          {
            required: true,
            trigger: 'change',
            message: this.$t('required', { field: '图类型' })
          }
        ],
        bannerResourceType: [
          {
            required: true,
            trigger: 'change',
            message: this.$t('required', { field: '商品类型' })
          }
        ],
        bannerResource: [
          {
            required: true,
            message: this.$t('required', { field: '关联项' }),
            trigger: 'change'
          }
        ],
        bannerLocation: [
          {
            required: true,
            message: this.$t('required', { field: '图地址' })
          }
        ]
      },

      single: false,
      bannerFileList: [],

      // -------- Picker ----------
      pickerModalVisible: false,
      pickerModalLoading: false,
      pickerType: ''
      // -------- !Picker ----------
    }
  },
  methods: {
    // --------------------------------------  request --------------------------------------

    // -------------------------------------- !request --------------------------------------
    handleUploadSuccess (res, file, fileList) {
      this.ruleForm.bannerLocation = res.data
      this.single = fileList.length === 1
    },

    handleUploadRemove (field, file, fileList) {
      this.ruleForm['bannerLocation'] = ''
      this.updateBannerFileList()
      this.single = false
    },

    handleUploadError (_, file, fileList) {
      this.$message.error(this.$t('fileUploadError'))
    },

    updateBannerFileList () {
      this.bannerFileList = this.ruleForm.bannerLocation
        .split(',')
        .filter(Boolean)
        .map((it) => {
          return {
            name: it,
            url: this.$V.staticBaseURL + it
          }
        })
      this.single = this.bannerFileList.length > 0
    },

    openPickerTable () {
      this.pickerType = +this.ruleForm.bannerResourceType
      this.pickerModalVisible = true
    },
    handleClose () {},

    beforeSubmit (ruleForm) {
      const { bannerResourceList, ...rest } = ruleForm
      return rest
    },

    // ------------------------------ picker 开始 ------------------------------
    getSelection () {
      let selected = this.$refs.picker.getSelection()

      return selected
    },

    handlePick () {
      try {
        this.$refs.picker.assertSelection()

        const goods = this.getSelection()
        this.ruleForm.bannerResourceList = goods
        this.pickerModalVisible = false
      } catch (err) {
        this.$message.warning(err.message)
      }
    }
    // ------------------------------ picker 结束 ------------------------------
  },
  computed: {
    bannerResourceTypes () {
      return this.$mapEnumToSelect(bannerResourceTypeEnum)
    },

    isCoupon () {
      return this.ruleForm.bannerResourceType === bannerResourceTypeEnum.coupon
    },

    isCategory () {
      return (
        this.ruleForm.bannerResourceType ===
        bannerResourceTypeEnum.freshCategory
      )
    },
    crossPick () {
      return !this.singlePick
    },
    singlePick () {
      return (
        this.ruleForm.bannerResourceType ===
          bannerResourceTypeEnum.freshCategory ||
        this.ruleForm.bannerResourceType ===
          bannerResourceTypeEnum.maintenanceCategory
      )
    },

    tagBoxProps () {
      if (this.isCoupon) {
        return { value: 'couponId', label: 'couponName' }
      }
      return this.isCategory
        ? { value: 'classifyId', label: 'classifyName' }
        : { value: 'goodsId', label: 'goodsName' }
    },

    primaryKey () {
      if (this.isCoupon) {
        return 'couponId'
      }
      return this.isCategory ? 'classifyId' : 'goodsId'
    },

    listLabel () {
      switch (this.ruleForm.bannerResourceType) {
        case bannerResourceTypeEnum.fresh:
          return '生鲜商品'
        case bannerResourceTypeEnum.maintenance:
        case bannerResourceTypeEnum.maintenanceCategory:
          return '维保商品'
        case bannerResourceTypeEnum.freshCategory:
          return '生鲜分类'
        default:
          return '商品'
      }
    }
  },

  created () {
    this.$watch('ruleForm.bannerResourceType', (val, lastVal) => {
      if (val && lastVal && val !== lastVal) {
        this.ruleForm.bannerResourceList = []
      }
      if (val === bannerResourceTypeEnum.coupon) {
        this.rules.bannerResource[0].required = false
      } else {
        this.rules.bannerResource[0].required = true
      }
    })

    this.$watch('ruleForm.bannerResourceList', (val) => {
      try {
        this.ruleForm.bannerResource = val
          .map((it) => it[this.primaryKey])
          .join(',')
      } catch (e) {}
    })
  },

  mounted () {
    this.updateBannerFileList()

    this.watchSelect('bannerType', 'bannerTypeValue', this.$attrs.bannerTypes)
  }
}
</script>
